package com.itheima.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.pojo.StatusCode;
import com.itheima.utils.CookieUtils;
import com.itheima.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    //设置token标签
    private static final String BEARER = "bearer_";
    //设置存入cookie的token键
    private static final String AUTHORIZATION = "Authorization";
    //设置redis中token的键标签
    private static final String LOGIN = "LOGIN_";

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 在请求处理之前进行调用（Controller方法调用之前）
     */


    @Override

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        try {
            String cookieToken = CookieUtils.getCookieValue(request, AUTHORIZATION);
            if (cookieToken != null) {
                System.out.println("::"+cookieToken);
                String token = cookieToken.replace(BEARER, "");
                Map<String, Object> map1 = TokenUtil.parserJavaWebToken(token);
                if (map1==null||map1.size()<=0){
                    response.setCharacterEncoding("utf-8");
                    response.setContentType("application/json; charset=utf-8");
                    PrintWriter writer = response.getWriter();
                    Map<String, Object> map = new HashMap<>();
                    map.put("code", StatusCode.ERROR);
                    map.put("data", "未登录");
                    writer.write(JSON.toJSONString(map));
                    return false;
                }
                String username =(String) map1.get("username");
                String redisToken = (String) redisTemplate.boundValueOps(LOGIN+username).get();
                if (redisToken==null){
                    response.setCharacterEncoding("utf-8");
                    response.setContentType("application/json; charset=utf-8");
                    PrintWriter writer = response.getWriter();
                    Map<String, Object> map = new HashMap<>();
                    map.put("code", StatusCode.ERROR);
                    map.put("data", "请先登录");
                    writer.write(JSON.toJSONString(map));
                    return false;
                }

                if (redisToken.equals(cookieToken)) {
                    return true;
                }

                redisTemplate.delete(LOGIN +username);
                response.setCharacterEncoding("utf-8");
                response.setContentType("application/json; charset=utf-8");
                PrintWriter writer = response.getWriter();
                Map<String, Object> map = new HashMap<>();
                map.put("code", StatusCode.ERROR);
                map.put("data", "账号过期请登录");
                writer.write(JSON.toJSONString(map));
                return false;
                //response.sendRedirect(request.getContextPath() + "登录路径或登录界面");
            }
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json; charset=utf-8");
            PrintWriter writer = response.getWriter();
            Map<String, Object> map = new HashMap<>();
            map.put("code", StatusCode.ERROR);
            map.put("data", "请先登录");
            writer.write(JSON.toJSONString(map));
            //response.sendRedirect(request.getContextPath() + "登录路径或登录界面");
            return false;

        } catch (Exception e) {

            e.printStackTrace();
            return false;
        }

        //如果设置为false时，被请求时，拦截器执行到此处将不会继续操作

        //如果设置为true时，请求将会继续执行后面的操作



    }



    /**
     * 请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
     */


    @Override

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {

//         System.out.println("执行了TestInterceptor的postHandle方法");

    }



    /**
     * 在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）
     */


    @Override

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

//        System.out.println("执行了TestInterceptor的afterCompletion方法");

    }


}